from django.conf import settings
from django.shortcuts import render
from rest_framework.generics import CreateAPIView, UpdateAPIView, GenericAPIView
from rest_framework.views import APIView
from random import randint
from django_redis import get_redis_connection
from rest_framework.response import Response
from celery_tasks.sms.tasks import send_sms_code
from meiduo_mall.libs.yuntongxun.sms import CCP
from threading import Thread
from users.models import User
from users.serializers import UserSerialziers, UserDetailSerializer, EmailSerializer, VerifySerizlizers
from rest_framework.generics import RetrieveAPIView
from itsdangerous import TimedJSONWebSignatureSerializer as TJS


class SMSCodeView(APIView):

    def get(self, request, mobile):
        # 判断发送频率 控制60s
        conn = get_redis_connection('verify')
        flag = conn.get('sms_flag_%s' % mobile)
        if flag:
            return Response({'errors': '请求过于频繁'}, status=402)
        # 生成一个短信验证码
        sms_code = '%06d' % randint(0, 999999)
        print(sms_code)
        # print(sms_code)

        # 保存短信验证码
        pl = conn.pipeline()
        pl.setex('sms_%s' % mobile, 300, sms_code)
        pl.setex('sms_flag_%s' % mobile, 60, 1)
        pl.execute()  # 传递指令  写入redis

        # 发送短信验证码
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, '1'], 1)
        send_sms_code.delay(mobile, sms_code)
        # t=Thread(target='send_email',kwargs=)
        # t.start()

        # 返回结果
        return Response({'message': 'ok'})


class UserNameCountView(APIView):

    def get(self, reqeust, username):
        # 查询数据对象数量
        count = User.objects.filter(username=username).count()

        return Response(
            {
                'count': count
            }
        )


class MobileCountView(APIView):

    def get(self, reqeust, mobile):
        # 查询数据对象数量
        count = User.objects.filter(mobile=mobile).count()

        return Response(
            {
                'count': count
            }
        )


class UserView(CreateAPIView):
    # serializers_class=UserSerialziers
    serializer_class = UserSerialziers

    # def post(self, request, *args, **kwargs):
    #
    #     # 验证数据
    #     ser = self.get_serializer(data=request.data)
    #
    #     ser.is_valid()
    #
    #     print(ser.errors)
    #
    #     response=super().post(request)
    #
    #     return response


class UserDetailView(RetrieveAPIView):
    serializer_class = UserDetailSerializer

    # serializer_class = UserDetailSerializer
    # queryset = User.objects.all()

    def get_object(self):
        return self.request.user


class UserEmailView(UpdateAPIView):
    serializer_class = EmailSerializer

    # def put(self,request):
    #
    #     # 获取数据
    #
    #     # 验证数据
    #
    #     # 更新数据
    #
    #     # 返回结果

    def get_object(self):
        return self.request.user


# class VerifyEmail(APIView):
#     def get(self, request):
#         # 获取token数据
#         token = request.query_params.get('token', None)
#         if token is None:
#             return Response({"errors", "缺少token"}, status=400)
#
#         # 解密token
#         tjs = TJS(settings.SECRET_KEY, 300)
#         try:
#             data = tjs.loads(token)
#         except:
#             return Response({'errors': '无效token'}, status=400)
#         # 获取加密打用户信息
#         id = data['id']
#
#         # 查询用户
#         user = User.objects.get(id=id)
#
#         # 更新验证状态
#         user.email_active = True
#         user.save()
#
#         # 返回结果
#         return Response({'message': 'ok'})
#
# class VerifyEmail(GenericAPIView):
#     serializer_class = VerifySerizlizers
#     def get(self, request):
#         # 获取token数据
#         data = request.query_params
#
#         # 验证数据
#         ser=self.get_serializer(data=data)
#         ser.is_valid()
#         #更新验证状态
#         ser.save()
#         # 返回结果
#         return Response({'message': 'ok'})

class VerifyEmail(CreateAPIView):
    serializer_class = VerifySerizlizers

    def get_serializer(self, *args, **kwargs):
        return super().get_serializer(data=self.request.query_params)

    def get(self, request):
        super().post(request)
        return Response({'message': 'ok'})
